import com.test.Book;

import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class Main {

    private static List LIST;

    public static void main(String[] args) {
        System.out.println("正在初始化图书管理系统...");
        load();
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("-------------图书管理系统-------------");
            System.out.println("1.录入书籍信息");
            System.out.println("2.查询书籍信息");
            System.out.println("3.删除书籍信息");
            System.out.println("4.修改书籍信息");
            System.out.println("5.退出系统");
            switch (scanner.nextInt()) {
                case 1: {
                    addBook(scanner);
                }

                case 2: {
                    listBook();
                }

                case 3: {
                    deleteBook(scanner);
                }

                case 4: {

                }

                case 5: {
                    System.out.println("正在保存书籍数据");
                    save();
                    System.out.println("感谢你的使用，再见");
                    break;
                }
            }
        }

    }

    @SuppressWarnings("unchecked")
    private static void load() {
        File file = new File("data");
        if (file.exists()) {
            try (ObjectInputStream stream = new ObjectInputStream(new FileInputStream(file))) {
                LIST = (List<Book>) stream.readObject();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            LIST = new LinkedList<>();
        }
    }

    private static void addBook(Scanner scanner) {
        scanner.nextLine();
        System.out.print("请输入书籍名称：");
        String title = scanner.nextLine();
        System.out.print("请输入作者名称：");
        String author = scanner.nextLine();
        System.out.print("请输入书籍价格：");
        int price = scanner.nextInt();
        scanner.nextLine();
        Book book = new Book(title, author, price);
        LIST.add(book);
        System.out.println("书籍信息添加成功" + book);
    }

    private static void save() {
        try (ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream("data"));) {
            stream.writeObject(LIST);
            stream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static void listBook() {
        for (int i = 0; i < LIST.size(); i++) {
            System.out.println(i + "." + LIST.get(i));
        }
    }

    private static void deleteBook(Scanner scanner) {
        scanner.nextLine();
        System.out.println("请输入要删除的书籍编号：");
        int index = scanner.nextInt();
        while (index >= LIST.size() || index < 0) {
            System.out.println("输入错误，请重新输入：");
        }
        LIST.remove(index);
        System.out.println("删除成功");
    }
}


